package com.ld.security.common.mybatis.util;

import com.ld.security.common.core.util.ReflectionUtil;
import com.ld.security.common.mybatis.anno.SqlKey;
import com.ld.security.common.mybatis.wrapper.BaseQueryWrapper;
import lombok.Data;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class SqlTool {

    public static List<fieldVo> groupField(Class clazz){
        HashMap<Integer,List<Field>> map =  new HashMap<>(50);
        for (Field field : ReflectionUtil.getAllDeclaredFields(clazz)) {
            SqlKey sqlKey = field.getAnnotation(SqlKey.class);
            int index=0;
            if(sqlKey != null){
                index = sqlKey.index();

            }
            List list =  map.get(index);
            if(list == null){
                list = new LinkedList();
                map.put(index,list);
            }
            list.add(field);
        }

        List<fieldVo> vo = new LinkedList<>();

        map.forEach((x,y) -> {
            fieldVo f = new fieldVo();
            f.setValue(x);
            f.setFields(y);
            vo.add(f);
        });

        vo.sort((x,y) -> {
            return x.getValue() - y.getValue();
        });

        return vo;

    }


    /**
     * 分组用的
     */
    @Data
    public static class fieldVo{
        private Integer value;
        private List<Field> fields;

        /**
         * 至少存在值
         * @param obj
         * @return
         */
        public boolean hasValue(Object obj){
          for (Field field : fields) {
              Object val = ReflectionUtil.invokeGetter(obj,field.getName());
            if(ReflectionUtil.isNotNull(val)){
                return true;
            }
          }
          return false;
        }

    }



}
